<?php

namespace app\admin\controller\pay;

use app\common\controller\Backend;
use think\Env;

/**
 * 支付订单
 *
 * @icon fa fa-user
 */
class Pay extends Backend
{
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Pay.Pay');
    }
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    public function del($ids = null)
    {
        $ids = $ids ?: $this->request->param('ids', 0, 'trim');

        $list = $this->model->select($ids);
        if (!$list) {
            $this->error('请选择需要删除订单');
        }
        $result = $this->model->destroy($ids);
        if ($result === false) {
            $this->error('删除失败');
        } else {
            $this->success('删除成功');
        }
    }
    public function supplementary()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->param('ids');
            $payList = $this->model->select($ids);
            if (count($payList) < 1) {
                $this->error('需要补单的订单不存在');
            }

            foreach ($payList as $pay) {
                // 下单地址
                $pay = $pay->toArray();
                $result1 = httpRequest($pay['callbackurl'],$pay);
                $result1 = json_decode($result1, true);
                if ($result1['code'] != 1) {
                    $this->error($pay['id'] . '支付订单出现' . $result1['msg']);
                }
                if ($pay['status'] != 1 && $result1['code'] == 1) {
                    $result = $this->model->where('id', $pay['id'])->update(['status' => '1']);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                }
            }
            $this->success('补单成功！');
        }
    }
}
